package network;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA
 * Description:
 * User: Administrator
 * Data: 2023 - 10 - 06
 * Time: 14:04
 */
public class UdpEchoClient {
     private DatagramSocket socket = null;
     private String serveIp = "";
     private int servePort = 0;
     public UdpEchoClient(String ip, int port) throws SocketException {
         socket = new DatagramSocket();
         serveIp = ip;
         servePort = port;
     }
     public void start() throws IOException {
         System.out.println("客户端启动！");
         Scanner scanner = new Scanner(System.in);
         while (true) {
             System.out.print("-> ");
             String request = scanner.next();
             DatagramPacket requestPacket = new DatagramPacket(request.getBytes(), request.getBytes().length,
                     InetAddress.getByName(serveIp), servePort);
             socket.send(requestPacket);
             DatagramPacket responPacket = new DatagramPacket(new byte[4096], 4096);
             socket.receive(responPacket);
             //将接收到的响应打印出来
             String respon = new String(responPacket.getData(), 0, responPacket.getLength());
             System.out.println(respon);
         }
     }

    public static void main(String[] args) throws IOException {
        UdpEchoClient udpEchoClient = new UdpEchoClient("127.0.0.1", 9090);
        udpEchoClient.start();
    }
}
